package com.dongdong.controller;

import com.alibaba.fastjson.JSONObject;
import com.dongdong.em.Result;
import com.dongdong.em.ResultEnum;
import com.dongdong.model.TbUser;
import com.dongdong.util.JWTUtil;
import com.dongdong.vo.UserVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("userlogin")
@RefreshScope   //热更新
public class LoginController {


    @Autowired
    private JWTUtil jwtUtil;

    @PostMapping("userlogin")
    public Result userlogin(@RequestParam String username, @RequestParam String password) {
        //1.获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2.封装数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
        //3.进入认证方法
        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException unknownAccountException) {
            unknownAccountException.printStackTrace();
            return Result.ZHRESPONSE(ResultEnum.USERNAME_PASSWORD_ERROR_DATA);
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return Result.ZHRESPONSE(ResultEnum.USERNAME_PASSWORD_ERROR_DATA);
        }

        //校验JWT   生成token
        TbUser usertoken = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //脱敏处理
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(usertoken, userVO);
        String token = jwtUtil.createJwt(userVO.getId().toString(), JSONObject.toJSONString(userVO), "roles");

        return Result.ZHRESPONSE(ResultEnum.LOGIN_SUCCESS_DATA).setData(token);
    }
}
